import os
import json
from datetime import datetime
from collections import defaultdict
from pyecharts import options as opts
from pyecharts.charts import Line
from pyecharts.globals import ThemeType

# 公共配置：关键号码和下注规则
TARGET_NUMBERS = ["01", "02", "03", "04"]  # 关键号码
BET_CONFIG = {
    "01": ["01", "06"],   # 01号码对应押注01和06
    "02": ["02", "07"],   # 02号码对应押注02和07
    "03": ["03", "08"],   # 03号码对应押注03和08
    "04": ["04", "09"]    # 04号码对应押注04和09
}

# 策略配置参数
STRATEGY_CONFIG = {
    "initial_capital": 1000,  # 初始本金
    "consecutive_bet_periods": 3,  # 连续投注期数上限
    "base_bet_amount": 5,  # 单注金额（每个号码的投注金额）
    "payout_ratio": 9.7052,  # 赔率
    "stop_capital_threshold": 1500  # 停止下注的本金阈值
}


def can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
    """检查当前本金是否足够支付一组投注（总投注金额=单注金额×总押注号码数）"""
    return current_capital >= base_bet_amount * total_bet_numbers


def group_data_by_date(data):
    """按日期分组数据并按期号升序排列"""
    daily_data = defaultdict(list)
    for item in data['items']:
        open_time = datetime.strptime(item['open_time'], "%Y-%m-%d %H:%M:%S")
        daily_data[open_time.date()].append(item)

    # 对每天的数据按期号升序排列
    for date in daily_data:
        daily_data[date] = sorted(daily_data[date], key=lambda x: int(x['issue_no']))

    return daily_data


def analyze_lottery(data, bet_config=BET_CONFIG, target_numbers=TARGET_NUMBERS, strategy_config=STRATEGY_CONFIG):
    """分析彩票数据，下注逻辑：当前期中奖个数不为0时，下一期开始新一轮投注，规定3期内中奖则停止本轮"""
    daily_data = group_data_by_date(data)
    daily_results = {}

    # 计算总押注号码数（用于计算投注金额）
    total_bet_numbers = sum(len(codes) for codes in bet_config.values())

    for date, items in daily_data.items():
        date_str = date.strftime("%Y-%m-%d")
        print(f"分析日期: {date_str}，共 {len(items)} 期数据")

        daily_result = {
            'date': date_str,
            'total_issues': len(items),
            'win_count': 0,  # 中奖总次数（每个匹配的号码都算一次）
            'bet_config': bet_config,
            'counter_data': [],
            'consecutive_bet_data': []  # 连续押注数据
        }

        # 从配置中获取参数
        initial_capital = strategy_config["initial_capital"]
        current_capital = initial_capital  # 当前本金
        payout_ratio = strategy_config["payout_ratio"]

        # 当日停止下注标记
        stop_betting_today = False

        # 连续投注跟踪变量
        remaining_bet_periods = 0  # 剩余连续投注期数（0表示不处于连续投注阶段）
        base_bet_amount = strategy_config["base_bet_amount"]  # 每个号码的下注金额
        trigger_next = False  # 标记下一期是否需要开始投注
        bet_round = 0  # 投注轮次
        current_round_won = False  # 当前轮是否已中奖

        # 从第二期开始分析（第一期无历史数据）
        for i in range(1, len(items)):
            current_issue = items[i]
            current_issue_no = current_issue['issue_no']
            current_open_code = current_issue['open_code']
            current_open_time = current_issue['open_time']
            current_codes = current_open_code.split(',')

            # 上一期数据
            prev_issue = items[i - 1]
            prev_issue_no = prev_issue['issue_no']
            prev_open_code = prev_issue['open_code']
            prev_codes = prev_open_code.split(',')

            # 提取上一期关键号码的位置
            positions_target = [
                {"pos": pos + 1, "code": code}
                for pos, code in enumerate(prev_codes)
                if code in target_numbers
            ]

            # 计算当前期中奖情况（支持多号码匹配）
            win_count = 0
            win_positions = []
            win_codes = []
            for target in positions_target:
                pos = target["pos"]
                prev_code = target["code"]
                if 0 <= pos - 1 < len(current_codes):
                    current_code = current_codes[pos - 1]
                    # 检查当前号码是否在押注列表中（支持多个号码）
                    if current_code in bet_config[prev_code]:
                        win_count += 1
                        win_positions.append(pos)
                        win_codes.append(current_code)

            # 更新累计数据
            daily_cumulative_issues = i  # 累计期数（从1开始）
            daily_cumulative_wins = daily_result['win_count'] + win_count  # 累计中奖数

            # 计数器计算
            counter = daily_cumulative_issues / 9.705 - daily_cumulative_wins
            daily_result['counter_data'].append({
                'issue_no': current_issue_no,
                'daily_cumulative_issues': daily_cumulative_issues,
                'daily_cumulative_wins': daily_cumulative_wins,
                'counter': counter,
                'open_time': current_open_time
            })

            # 更新总中奖数
            daily_result['win_count'] += win_count

            # 下注逻辑
            previous_capital = current_capital  # 记录调整前的本金
            current_bet_amount = 0  # 当期总下注金额（单注金额×总押注号码数）
            current_profit = 0  # 当期盈利
            betting = False  # 是否处于投注状态
            round_ended = False  # 当前轮是否结束
            stopped_by_capital = False  # 是否因本金达到阈值停止下注
            stopped_by_insufficient_funds = False  # 是否因资金不足停止下注

            # 检查是否因本金达到阈值停止下注
            if current_capital > strategy_config["stop_capital_threshold"]:
                stop_betting_today = True
                stopped_by_capital = True

            # 执行连续投注（剩余期数>0时）
            if remaining_bet_periods > 0 and not stop_betting_today:
                # 检查本金是否足够支付当前投注（总金额=单注金额×总押注号码数）
                if can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
                    betting = True
                    current_bet_amount = base_bet_amount * total_bet_numbers  # 计算总投注金额
                    # 盈利计算公式：中奖个数×单注金额×赔率 - 总投注金额
                    current_profit = win_count * base_bet_amount * payout_ratio - current_bet_amount
                    current_capital += current_profit  # 更新本金

                    # 如果在投注期内中奖，停止本轮投注
                    if win_count > 0:
                        current_round_won = True
                        remaining_bet_periods = 0  # 剩余期数设为0，结束本轮
                        round_ended = True
                    else:
                        remaining_bet_periods -= 1  # 剩余期数减1
                else:
                    # 资金不足，停止当天投注
                    stop_betting_today = True
                    stopped_by_insufficient_funds = True

            # 检查是否需要开始新的连续投注（由上一期触发）
            elif trigger_next and not stop_betting_today:
                # 检查本金是否足够支付一组投注
                if can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
                    betting = True
                    bet_round += 1  # 开始新的一轮
                    current_round_won = False  # 重置轮次中奖状态

                    current_bet_amount = base_bet_amount * total_bet_numbers  # 计算总投注金额
                    current_profit = win_count * base_bet_amount * payout_ratio - current_bet_amount
                    current_capital += current_profit

                    remaining_bet_periods = strategy_config["consecutive_bet_periods"] - 1  # 剩余期数
                    trigger_next = False  # 重置触发标记

                    # 如果第一轮投注就中奖，立即结束本轮
                    if win_count > 0:
                        current_round_won = True
                        remaining_bet_periods = 0
                        round_ended = True
                else:
                    # 资金不足，停止当天投注
                    stop_betting_today = True
                    stopped_by_insufficient_funds = True
                    trigger_next = False  # 重置触发标记

            # 连续中奖统计
            current_streak = 1 if win_count > 0 else 0
            if daily_result['consecutive_bet_data']:
                last_bet = daily_result['consecutive_bet_data'][-1]
                current_streak = last_bet['current_streak'] + 1 if win_count > 0 else 0
            max_streak = max(
                [bet['current_streak'] for bet in daily_result['consecutive_bet_data']] + [current_streak]
            ) if daily_result['consecutive_bet_data'] else current_streak

            # 格式化下注位置（显示所有押注的号码）
            bet_pos_display = []
            for target in positions_target:
                pos = target["pos"]
                code = target["code"]
                bet_codes = bet_config[code]
                bet_pos_display.append(f"{pos}({'/'.join(bet_codes)})")

            # 记录当期数据
            daily_result['consecutive_bet_data'].append({
                'prev_issue_no': prev_issue_no,
                'current_issue_no': current_issue_no,
                'prev_open_code': prev_open_code,
                'bet_positions': ", ".join(bet_pos_display),
                'current_open_code': current_open_code,
                'win_count': win_count,
                'win_positions': win_positions,
                'win_codes': win_codes,
                'current_streak': current_streak,
                'max_streak': max_streak,
                'open_time': current_open_time,
                'daily_cumulative_issues': daily_cumulative_issues,
                'daily_cumulative_wins': daily_cumulative_wins,
                'counter': counter,
                'betting': betting,  # 是否在投注期
                'base_bet_amount': base_bet_amount,
                'total_bet_numbers': total_bet_numbers,  # 总押注号码数
                'bet_amount': current_bet_amount,
                'profit': current_profit,
                'previous_capital': previous_capital,
                'current_capital': current_capital,
                'remaining_bet_periods': remaining_bet_periods,
                'trigger_next': trigger_next,
                'win_in_current': win_count > 0,
                'bet_round': bet_round,
                'current_round_won': current_round_won,
                'round_ended': round_ended,
                'stop_betting_today': stop_betting_today,
                'stopped_by_capital': stopped_by_capital,
                'stopped_by_insufficient_funds': stopped_by_insufficient_funds
            })

            # 核心逻辑：当前期中奖个数不为0时，下一期开始新一轮投注
            if win_count > 0 and remaining_bet_periods == 0 and not stop_betting_today:
                # 检查本金是否足够支付下一组投注
                if can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
                    trigger_next = True  # 当前期中奖且不在投注期，下一期开始投注
                else:
                    trigger_next = False  # 资金不足，不触发投注
            else:
                trigger_next = False

        # 保存最大连胜次数
        daily_result['max_streak'] = max(
            [bet['max_streak'] for bet in daily_result['consecutive_bet_data']]
        ) if daily_result['consecutive_bet_data'] else 0

        # 计算当天总盈利
        if daily_result['consecutive_bet_data']:
            daily_result['daily_profit'] = daily_result['consecutive_bet_data'][-1]['current_capital'] - initial_capital
        else:
            daily_result['daily_profit'] = 0

        daily_results[date] = daily_result

    return daily_results


def generate_counter_chart(counter_data, output_dir, date_str):
    """生成计数器折线图"""
    if not counter_data:
        return None

    sorted_counter_data = sorted(
        counter_data,
        key=lambda x: int(x['issue_no'])
    )

    issue_nos = [item['issue_no'] for item in sorted_counter_data]
    counters = [item['counter'] for item in sorted_counter_data]

    tooltip_data = [
        f"期号: {item['issue_no']}<br/>开奖时间: {item['open_time']}<br/>计数器: {item['counter']:.2f}"
        for item in sorted_counter_data
    ]

    line = (
        Line(init_opts=opts.InitOpts(
            theme=ThemeType.LIGHT,
            width="1000px",
            height="500px"
        ))
        .add_xaxis(issue_nos)
        .add_yaxis(
            "计数器",
            counters,
            is_smooth=True,
            label_opts=opts.LabelOpts(is_show=False),
            itemstyle_opts=opts.ItemStyleOpts(color="#3398DB")
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title=f"{date_str} 计数器变化趋势"),
            xaxis_opts=opts.AxisOpts(
                name="期号",
                axislabel_opts=opts.LabelOpts(rotate=60)
            ),
            yaxis_opts=opts.AxisOpts(
                name="计数器值",
                splitline_opts=opts.SplitLineOpts(is_show=True)
            ),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            tooltip_opts=opts.TooltipOpts(
                trigger="axis",
                formatter=lambda params: tooltip_data[params[0].data_index]
            ),
            datazoom_opts=[opts.DataZoomOpts()]
        )
    )

    chart_file = os.path.join(output_dir, f"counter_chart_{date_str}.html")
    line.render(chart_file)
    return chart_file


def generate_html_report(daily_result, data, output_dir,TARGET_NUMBERS,BET_CONFIG, strategy_config=STRATEGY_CONFIG):
    """生成每日分析报告HTML"""
    date_str = daily_result['date']
    output_file = os.path.join(output_dir, f"lottery_analysis_{date_str}.html")

    # 基础统计
    total_issues = daily_result['total_issues'] - 1  # 总投注期数
    total_wins = daily_result['win_count']
    win_rate = f"{(total_wins / total_issues * 100) if total_issues > 0 else 0:.2f}%"

    # 配置显示
    config_display = ", ".join([f"{code}→{'/'.join(codes)}" for code, codes in daily_result['bet_config'].items()])
    total_bet_numbers = sum(len(codes) for codes in daily_result['bet_config'].values())  # 总押注号码数

    # 计数器图表
    counter_chart = generate_counter_chart(daily_result['counter_data'], output_dir, date_str)
    chart_iframe = f'<iframe src="{os.path.basename(counter_chart)}" width="100%" height="550" frameborder="0"></iframe>' if (
            counter_chart and os.path.exists(counter_chart)) else '<div>无数据生成图表</div>'

    # 盈利统计
    consecutive_data = daily_result['consecutive_bet_data']
    final_capital = consecutive_data[-1]['current_capital'] if consecutive_data else strategy_config["initial_capital"]
    total_profit = final_capital - strategy_config["initial_capital"]

    # 连续投注表格
    bet_table_html = ""
    for bet in consecutive_data:
        bet_positions = bet['bet_positions']
        win_positions = ", ".join(map(str, bet['win_positions'])) if bet['win_positions'] else "无中奖"
        win_codes = ", ".join(bet['win_codes']) if bet['win_codes'] else ""
        row_class = ' class="win"' if bet['win_count'] > 0 else ''
        if bet['betting']:
            row_class += ' betting'  # 投注期高亮
        if bet['stopped_by_capital']:
            row_class += ' stopped-by-capital'
        if bet['stopped_by_insufficient_funds']:
            row_class += ' stopped-by-insufficient-funds'

        # 盈利显示格式化
        profit_display = f"{bet['profit']:.2f}"
        if bet['profit'] > 0:
            profit_display = f"<span style='color:green'>+{profit_display}</span>"
        elif bet['profit'] < 0:
            profit_display = f"<span style='color:red'>{profit_display}</span>"

        # 标记触发投注和轮次结束的行
        trigger_class = ' class="trigger-bet"' if bet['trigger_next'] else ''
        round_end_class = ' class="round-end"' if bet['round_ended'] else ''

        bet_table_html += f"""
            <tr{row_class}{trigger_class}{round_end_class}>
                <td>{bet['prev_issue_no']}</td>
                <td>{bet['prev_open_code']}</td>
                <td>{bet_positions}</td>
                <td>{bet['current_issue_no']}</td>
                <td>{bet['current_open_code']}</td>
                <td>{win_positions}</td>
                <td>{win_codes}</td>
                <td>{bet['win_count']}</td>
                <td>{bet['current_streak']}</td>
                <td>{bet['daily_cumulative_issues']}</td>
                <td>{bet['daily_cumulative_wins']}</td>
                <td style="font-weight: bold;">{bet['counter']:.2f}</td>
                <td>{bet['open_time']}</td>
                <td>{'是' if bet['betting'] else '否'}</td>
                <td>{bet['base_bet_amount']}元/号</td>
                <td>{bet['total_bet_numbers']}个号码</td>
                <td>{bet['bet_amount'] if bet['betting'] else '-'}</td>
                <td>{profit_display}</td>
                <td style="font-weight: bold;">{bet['current_capital']:.2f}</td>
                <td>{bet['remaining_bet_periods']}</td>
                <td>{'是' if bet['trigger_next'] else '否'}</td>
                <td>{'是' if bet['win_in_current'] else '否'}</td>
                <td>{bet['bet_round']}</td>
                <td>{'是' if bet['current_round_won'] else '否'}</td>
                <td>{'是' if bet['round_ended'] else '否'}</td>
                <td>{'是' if bet['stop_betting_today'] else '否'}</td>
                <td>{'是' if bet['stopped_by_insufficient_funds'] else '否'}</td>
            </tr>
        """

    # HTML内容
    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{date_str} 彩票下注分析报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        h1 {{ color: #333; text-align: center; }}
        .stats-box, .config-box {{ padding: 15px; border-radius: 5px; margin-bottom: 20px; }}
        .stats-box {{ background-color: #f0f0f0; }}
        .config-box {{ background-color: #e6f7ff; }}
        .chart-box {{ margin: 30px 0; padding: 15px; background-color: #f8f9fa; border-radius: 5px; }}
        .table-container {{ overflow-x: auto; margin: 30px 0; }}
        table {{ width: 100%; border-collapse: collapse; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #e6e6e6; }}
        tr:nth-child(even) {{ background-color: #f9f9f9; }}
        .win {{ background-color: #d4edda; }}
        .betting {{ outline: 2px solid #3b82f6; }}
        .trigger-bet {{ outline: 2px solid #f59e0b; }}
        .round-end {{ outline: 2px solid #ef4444; }}
        .stopped-by-capital {{ outline: 2px solid #8b5cf6; }}
        .stopped-by-insufficient-funds {{ outline: 2px solid #10b981; }}
        .nav {{ margin-bottom: 20px; text-align: center; }}
        .nav a {{ margin: 0 10px; text-decoration: none; color: #0066cc; }}
        .profit-summary {{ margin: 20px 0; padding: 15px; background-color: #e6f7ff; border-radius: 5px; }}
    </style>
</head>
<body>
    <div class="nav">
        <a href="index.html">返回总览</a>
        <a href="summary.html">查看汇总报告</a>
    </div>
    <h1>{date_str} 彩票下注分析报告</h1>

    <div class="config-box">
        <h3>下注规则配置</h3>
        <div>规则: {config_display}</div>
        <div>初始本金: {strategy_config["initial_capital"]}元</div>
        <div>连续投注期数上限: {strategy_config["consecutive_bet_periods"]}期</div>
        <div>单注金额(每个号码): {strategy_config["base_bet_amount"]}元</div>
        <div>总押注号码数: {total_bet_numbers}个</div>
        <div>每组投注金额: {strategy_config["base_bet_amount"]} × {total_bet_numbers} = {strategy_config["base_bet_amount"] * total_bet_numbers}元</div>
        <div>赔率: {strategy_config["payout_ratio"]}</div>
        <div>停止下注阈值: 本金 > {strategy_config["stop_capital_threshold"]}元</div>
    </div>

    <div class="stats-box">
        <h3>当日统计数据</h3>
        <div>总期数: {daily_result['total_issues']}</div>
        <div>投注期数: {total_issues}</div>
        <div>中奖总次数: {total_wins}</div>
        <div>整体中奖率: {win_rate}</div>
        <div>最大连胜次数: {daily_result['max_streak']} 次</div>
    </div>

    <div class="profit-summary">
        <h3>盈利统计</h3>
        <div>初始本金: {strategy_config["initial_capital"]:.2f}</div>
        <div>最终本金: {final_capital:.2f}</div>
        <div>总盈利: <span style="color:{'green' if total_profit > 0 else 'red'}">{total_profit:+.2f}</span></div>
    </div>

    <div class="chart-box">
        <h3>计数器变化趋势</h3>
        <p>计数器 = 累计总期数 / 9.705 - 累计中奖个数</p>
        {chart_iframe}
    </div>

    <div class="table-container">
        <h3>每日投注中奖情况</h3>
        <p>下注策略：初始本金{strategy_config["initial_capital"]}元，<strong>当前期中奖个数不为0时，下一期开始投注；若在接下来的{strategy_config["consecutive_bet_periods"]}期内中奖，则立即停止投注；当剩余本金>{strategy_config["stop_capital_threshold"]}时，当天停止下注；若剩余本金不足单组金额（{strategy_config["base_bet_amount"]}元×{total_bet_numbers}={strategy_config["base_bet_amount"] * total_bet_numbers}元），也停止下注</strong></p>
        <p>盈利公式：当期盈利 = 中奖个数 × {strategy_config["base_bet_amount"]} × {strategy_config["payout_ratio"]} - {strategy_config["base_bet_amount"]} × {total_bet_numbers}</p>
        <p>表格说明：</p>
        <ul>
            <li>绿色背景：当期有中奖</li>
            <li>蓝色边框：当期处于投注期</li>
            <li>橙色边框：当期触发下一期开始投注（当前期中奖但未投注）</li>
            <li>红色边框：当前轮次结束（可能是因为中奖或达到{strategy_config["consecutive_bet_periods"]}期）</li>
            <li>紫色边框：因本金>{strategy_config["stop_capital_threshold"]}停止下注的期</li>
            <li>青绿色边框：因本金不足单组金额停止下注的期</li>
        </ul>

        <table>
            <tr>
                <th>上一期期号</th>
                <th>上一期开奖号码</th>
                <th>下注位置(位置+号码)</th>
                <th>当前期期号</th>
                <th>当前期开奖号码</th>
                <th>中奖位置</th>
                <th>中奖号码</th>
                <th>中奖个数</th>
                <th>当前连胜</th>
                <th>累计期数</th>
                <th>累计中奖</th>
                <th>计数器</th>
                <th>开奖时间</th>
                <th>是否投注</th>
                <th>单注金额</th>
                <th>总押注号码</th>
                <th>总下注</th>
                <th>当期盈利</th>
                <th>当前本金</th>
                <th>剩余投注期数</th>
                <th>触发下一期</th>
                <th>当前期是否中奖</th>
                <th>投注轮次</th>
                <th>轮次是否已中奖</th>
                <th>轮次是否结束</th>
                <th>停止下注</th>
                <th>资金不足</th>
            </tr>
            {bet_table_html}
        </table>
    </div>
</body>
</html>
    """

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)
    return output_file


def generate_index_html(dates, output_dir):
    """生成索引页面"""
    output_file = os.path.join(output_dir, "index.html")
    html_content = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>彩票下注分析报告总览</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { color: #333; text-align: center; }
        .date-list { max-width: 800px; margin: 0 auto; }
        .date-item { margin: 10px 0; padding: 10px; background-color: #f0f0f0; border-radius: 5px; }
        .date-item a { text-decoration: none; color: #0066cc; }
        .summary-link { text-align: center; margin: 20px 0; }
    </style>
</head>
<body>
    <div class="summary-link">
        <a href="summary.html">查看汇总报告</a>
    </div>
    <h1>彩票下注分析报告总览</h1>
    <div class="date-list">
    """

    for date in sorted(dates):
        date_str = date.strftime("%Y-%m-%d")
        html_content += f"""
        <div class="date-item">
            <a href="lottery_analysis_{date_str}.html">{date_str}</a>
        </div>
        """

    html_content += """
    </div>
</body>
</html>
    """

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)
    return output_file


def generate_summary_html(daily_results, output_dir, strategy_config=STRATEGY_CONFIG):
    """生成汇总界面"""
    output_file = os.path.join(output_dir, "summary.html")

    # 按月统计（过滤投注期数≥1070的天）
    monthly_data = defaultdict(list)
    valid_daily_results = []

    for date, result in daily_results.items():
        total_issues = result['total_issues'] - 1
        if total_issues >= 1070:
            year_month = f"{date.year}-{date.month:02d}"
            monthly_data[year_month].append(result)
            valid_daily_results.append(result)

    # 每月平均中奖次数
    monthly_avg_win_counts = {}
    for year_month, results in monthly_data.items():
        total_win_count = sum(result['win_count'] for result in results)
        monthly_avg_win_counts[year_month] = {
            'days': len(results),
            'avg_win_count': total_win_count / len(results)
        }

    # 总平均中奖次数
    total_avg_win_count = sum(result['win_count'] for result in valid_daily_results) / len(
        valid_daily_results) if valid_daily_results else 0

    # 最大计数器平均值
    total_max_counter = 0
    valid_counter_days = 0
    for result in valid_daily_results:
        if result['counter_data']:
            total_max_counter += max(item['counter'] for item in result['counter_data'])
            valid_counter_days += 1
    avg_max_counter = total_max_counter / valid_counter_days if valid_counter_days else 0

    # 按月统计每天总盈利
    monthly_profit_data = defaultdict(list)
    for date, result in daily_results.items():
        year_month = f"{date.year}-{date.month:02d}"
        daily_profit = result.get('daily_profit', 0)
        monthly_profit_data[year_month].append({
            'date': date.strftime("%Y-%m-%d"),
            'profit': daily_profit
        })

    # 计算每月总盈利和平均每日盈利
    monthly_profit_summary = {}
    for year_month, profit_data in monthly_profit_data.items():
        total_profit = sum(item['profit'] for item in profit_data)
        avg_daily_profit = total_profit / len(profit_data)
        monthly_profit_summary[year_month] = {
            'total_profit': total_profit,
            'avg_daily_profit': avg_daily_profit,
            'days': len(profit_data),
            'profit_data': profit_data
        }

    # HTML内容
    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>彩票下注分析汇总报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        h1 {{ color: #333; text-align: center; }}
        .section {{ margin: 30px 0; padding: 15px; background-color: #f8f9fa; border-radius: 5px; }}
        .stats-box {{ background-color: #f0f0f0; padding: 15px; margin-bottom: 20px; }}
        .table-container {{ overflow-x: auto; margin: 30px 0; }}
        table {{ width: 100%; border-collapse: collapse; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; }}
        th {{ background-color: #e6e6e6; }}
        .profit-positive {{ color: green; }}
        .profit-negative {{ color: red; }}
        .below-threshold {{ background-color: #f5f5f5; }}
        .nav {{ margin-bottom: 20px; text-align: center; }}
        .nav a {{ margin: 0 10px; text-decoration: none; color: #0066cc; }}
        .avg-stats {{ background-color: #e6f7ff; padding: 10px; margin-bottom: 15px; border-radius: 5px; }}
        .month-header {{ background-color: #e6f7ff; padding: 10px; margin: 10px 0; border-radius: 5px; }}
        .monthly-profit-summary {{ background-color: #d1e7dd; padding: 15px; margin-bottom: 20px; border-radius: 5px; }}
        .monthly-profit-table {{ margin-top: 10px; }}
        .monthly-profit-table th, .monthly-profit-table td {{ border: 1px solid #ddd; padding: 8px; text-align: center; }}
        .monthly-profit-table th {{ background-color: #c1d6e1; }}
        .monthly-profit-total {{ font-weight: bold; }}
    </style>
</head>
<body>
    <div class="nav">
        <a href="index.html">返回日期列表</a>
    </div>
    <h1>彩票下注分析汇总报告</h1>

    <div class="stats-box">
        <h3>下注规则说明</h3>
        <div>初始本金{strategy_config["initial_capital"]}元，<strong>当前期中奖个数不为0时，下一期开始投注；若在接下来的{strategy_config["consecutive_bet_periods"]}期内中奖，则立即停止投注；当剩余本金>{strategy_config["stop_capital_threshold"]}时，当天停止下注；若剩余本金不足单组金额（单注金额×总押注号码数），也停止下注</strong></div>
        <div>盈利公式：当期盈利 = 中奖个数 × {strategy_config["base_bet_amount"]} × {strategy_config["payout_ratio"]} - {strategy_config["base_bet_amount"]} × 总押注号码数</div>
    </div>

    <div class="section monthly-profit-summary">
        <h2>按月份统计每日总盈利</h2>
        <div class="avg-stats">
            <p>统计了 <strong>{len(daily_results)}</strong> 天的数据</p>
        </div>
    """

    # 生成每月盈利汇总表格
    for year_month in sorted(monthly_profit_summary.keys()):
        month_data = monthly_profit_summary[year_month]
        total_profit = month_data['total_profit']
        avg_daily_profit = month_data['avg_daily_profit']
        days = month_data['days']

        total_profit_display = f"{total_profit:+.2f}"
        total_profit_class = "profit-positive" if total_profit >= 0 else "profit-negative"

        avg_daily_profit_display = f"{avg_daily_profit:+.2f}"
        avg_daily_profit_class = "profit-positive" if avg_daily_profit >= 0 else "profit-negative"

        daily_profit_rows = ""
        for item in sorted(month_data['profit_data'], key=lambda x: x['date']):
            profit = item['profit']
            profit_display = f"{profit:+.2f}"
            profit_class = "profit-positive" if profit >= 0 else "profit-negative"
            daily_profit_rows += f"""
                <tr>
                    <td>{item['date']}</td>
                    <td class="{profit_class}">{profit_display}</td>
                </tr>
            """

        html_content += f"""
        <div class="month-header">
            <h3>{year_month}（有效天数：{days}）</h3>
            <p>月总盈利：<span class="{total_profit_class}"><strong>{total_profit_display}</strong></span> 元</p>
            <p>平均每日盈利：<span class="{avg_daily_profit_class}"><strong>{avg_daily_profit_display}</strong></span> 元</p>
        </div>
        <div class="monthly-profit-table">
            <table>
                <tr>
                    <th>日期</th>
                    <th>当日总盈利（元）</th>
                </tr>
                {daily_profit_rows}
            </table>
        </div>
        """

    html_content += """
    </div>

    <div class="section">
        <h2>按月统计中奖次数平均值</h2>
        <p>统计投注期数≥1070的天，每月平均中奖次数</p>
        <div class="avg-stats">
            <p>有效天数共 <strong>""" + str(
        len(valid_daily_results)) + """</strong> 天，总平均每天中奖 <strong>""" + f"{total_avg_win_count:.2f}" + """</strong> 次</p>
        </div>
    """

    for year_month in sorted(monthly_avg_win_counts.keys()):
        data = monthly_avg_win_counts[year_month]
        html_content += f"""
            <div class="month-header">
                <h3>{year_month}（有效天数：{data['days']}）</h3>
                <p>平均每天中奖：<strong>{data['avg_win_count']:.2f}</strong> 次</p>
            </div>
        """

    html_content += """
        </div>
    </div>

    <div class="section">
        <h2>每天中奖个数统计</h2>
        <div class="avg-stats">
            <p>有效天数共 <strong>""" + str(
        len(valid_daily_results)) + """</strong> 天，平均每天中奖 <strong>""" + f"{total_avg_win_count:.2f}" + """</strong> 次</p>
        </div>
        <div class="table-container">
            <table>
                <tr><th>日期</th><th>投注期数</th><th>中奖次数</th><th>中奖率</th><th>最大连胜</th></tr>
    """

    for date, result in sorted(daily_results.items()):
        date_str = date.strftime("%Y-%m-%d")
        total_issues = result['total_issues'] - 1
        win_count = result['win_count']
        win_rate = f"{(win_count / total_issues * 100) if total_issues else 0:.2f}%"
        row_class = ' class="below-threshold"' if total_issues < 1070 else ''

        html_content += f"""
                <tr{row_class}>
                    <td>{date_str}</td><td>{total_issues}</td><td>{win_count}</td><td>{win_rate}</td><td>{result['max_streak']}</td>
                </tr>
        """

    html_content += """
            </table>
        </div>
        <p style="color: #888;">注：灰色背景表示投注期数<1070（不参与平均计算）</p>
    </div>

    <div class="section">
        <h2>每天最大计数器值</h2>
        <div class="avg-stats">
            <p>有效天数共 <strong>""" + str(
        len(valid_daily_results)) + """</strong> 天，平均最大计数器 <strong>""" + f"{avg_max_counter:.2f}" + """</strong></p>
        </div>
        <div class="table-container">
            <table>
                <tr><th>日期</th><th>最大计数器值</th><th>期号</th><th>开奖时间</th></tr>
    """

    for date, result in daily_results.items():
        date_str = date.strftime("%Y-%m-%d")
        total_issues = result['total_issues'] - 1
        row_class = ' class="below-threshold"' if total_issues < 1070 else ''

        if result['counter_data']:
            max_counter = max(item['counter'] for item in result['counter_data'])
            max_item = next(item for item in result['counter_data'] if item['counter'] == max_counter)
            max_counter_display = f"{max_counter:.2f}"
            issue_no = max_item['issue_no']
            open_time = max_item['open_time']
        else:
            max_counter_display = "-"
            issue_no = "-"
            open_time = "-"

        html_content += f"""
                <tr{row_class}>
                    <td>{date_str}</td><td><strong>{max_counter_display}</strong></td><td>{issue_no}</td><td>{open_time}</td>
                </tr>
        """

    html_content += """
            </table>
        </div>
    </div>
</body>
</html>
    """

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)
    return output_file


def main():
    """主函数"""
    json_file = "spider_jssc_data_20250716/merged_20250716_083522.json"  # 替换为实际JSON路径
    output_dir = "lottery_reports/赛车/一个17/组合计数器"
    os.makedirs(output_dir, exist_ok=True)

    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)

        daily_results = analyze_lottery(data)
        if not daily_results:
            print("警告: 无有效数据")
            return

        print("生成每日报告...")
        for date, result in daily_results.items():
            generate_html_report(result, data, output_dir)

        generate_index_html(daily_results.keys(), output_dir)
        generate_summary_html(daily_results, output_dir)
        print("所有报告生成完成")

    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    main()